package cn.lysj.framework.common.security.jwt;

import cn.lysj.framework.common.CommonConstant;
import cn.lysj.framework.common.annotation.CurrentUser;
import cn.lysj.framework.common.domain.User;
import cn.lysj.framework.common.exception.MyException;
import cn.lysj.framework.common.service.UserService;
import cn.lysj.framework.common.utils.web.ParamUtil;
import cn.lysj.framework.store.domain.Store;
import cn.lysj.framework.store.service.StoreService;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Resource;

/**
 * @author zk
 * @date 2018-08-14 4:01
 * @Description 增加方法注入，将含有 @CurrentUser 注解的方法参数注入当前登录用户
 */
public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Resource
    private UserService userService;
    @Resource
    private StoreService storeService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(User.class)
                && parameter.hasParameterAnnotation(CurrentUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String username = (String) webRequest.getAttribute("username", RequestAttributes.SCOPE_REQUEST);
        String userId = (String) webRequest.getAttribute("userId", RequestAttributes.SCOPE_REQUEST);
        User user = null;
        if (!ParamUtil.isBlank(userId)) {
            user = userService.findOne(userId);
        }
        if (!ParamUtil.isBlank(username)) {
            user = userService.findByUsername(username);
        }
        if (user == null) {
            throw new MyException("获取用户信息失败");
        }
        if (user.getDelFlag().equals(CommonConstant.DEL_FLAG)) {
            throw new MyException("用户已被禁用");
        }
        user.setStore(storeService.findByUserId(user.getId()));
        return user;
    }
}
